/**
 * Copyright (c) 2009-2011, chunquedong(YangJiandong)
 * 
 * This file is part of ChunMap project
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE(Version >=3)
 * 
 * History:
 *     2010-05-05  Jed Young  Creation
 */
package chunmap.app;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import chunmap.view.Map;

/**
 * 地图渲染线程
 * @author chunquedong
 * 
 */
public class RenderThread {
	
	private Render rendering;
	private Future<?> future;
	private final ExecutorService exe = Executors.newSingleThreadExecutor();
	
	private List<RenderListener> listener=new ArrayList<RenderListener>();
	
	
	
	public void startRender(Map map) {
		if(rendering!=null){
			rendering.cancel();
			if (future != null) {
				future.cancel(true);
			}
		}
		rendering = new Render(map);
		future = exe.submit(rendering);
	}
	
	public void cancel(){
		rendering.cancel();
		if (future != null) {
			future.cancel(true);
		}
	}
	
	private class Render implements Runnable {
		private volatile boolean canceled = false;
		private Map map;
		
		public Render(Map map){
			this.map=map;
		}
		
		public void run() {
			map.render();

			if (!canceled) {
				renderFinish();
			}
		}

		public void cancel() {
			this.canceled = true;
		}
	}
	
	//----------------------------------------------------------------渲染事件
	
	private void renderFinish() {
		for(RenderListener r:listener){
			r.renderFinished();
		}
	}
	
	public void addListener(RenderListener r){
		listener.add(r);
	}
	
	public void removeListener(RenderListener r){
		listener.remove(r);
	}
	
	public interface RenderListener{
		public void renderFinished();
	}
}